<template>
  <div id="app">
    <div class="header">
      <el-input
        v-model="topicInput"
        placeholder="请输入题目内容"
        clearable
        style="width: 200px; margin-right: 10px;"
      />
      <el-input
        v-model="typeInput"
        placeholder="请输入题目类型"
        clearable
        style="width: 200px; margin-right: 10px;"
      />
      <el-input
        v-model="scoreInput"
        placeholder="请输入分数"
        clearable
        style="width: 150px; margin-right: 10px;"
      />
      <el-button type="primary" icon="el-icon-search" @click="handleSearch">
        搜索
      </el-button>
      <el-button style="margin-left: 10px;" @click="handleReset">
        重置
      </el-button>
    </div>
    <div class="content">
      <div class="toolbar">
        <el-button type="primary" @click="handleCreate">创建题目</el-button>
        <el-button
          type="danger"
          :disabled="!selectedRows.length"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>
      <el-table
        :data="tableData"
        border
        header-align="center"
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="80" align="center" />
        <el-table-column prop="topic" label="题目内容" align="center" width="350" />
        <el-table-column label="选项" align="center" width="500">
          <template slot-scope="scope">
            <div class="option-grid">
              <div
                v-for="(option, index) in scope.row.content"
                :key="option.id"
              >
                <span
                  :style="{
                    color: option.is_ok === 1 ? 'green' : 'inherit',
                    fontWeight: option.is_ok === 1 ? 'bold' : 'normal'
                  }"
                >
                  {{ getOptionLetter(index) }}. {{ option.content }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type.name" label="题目类型" align="center" width="200" />
        <el-table-column prop="score" label="分数" align="center" width="200" />
        <el-table-column label="正确答案" align="center" width="200">
          <template slot-scope="scope">
            {{ getOptionLetter(scope.row.answer_index) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleManageTopic(scope.row)">编辑</el-button>
            <el-button
              :title="scope.row.isInUse ? '无法删除' : '删除'"
              :disabled="scope.row.isInUse"
              type="text"
              size="mini"
              style="color: #F56C6C;"
              @click="handleDeleteRow(scope.row)"
            >
              删除
            </el-button>
            <el-dropdown @command="handleCommand($event, scope.row)">
              <el-button type="text" style="margin-left: 10px;">
                <i class="el-icon-more" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="toDetail">查看详情</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 16px; text-align: center;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      title="题目详情"
      :visible.sync="detailDialogVisible"
      width="700px"
    >
      <div v-if="currentDetail">
        <el-descriptions border column="2" size="medium">
          <el-descriptions-item label="题目内容" :span="2" label-class-name="desc-label">
            <div style="white-space: pre-wrap;">
              {{ currentDetail.topic }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="题目类型" label-class-name="desc-label">
            {{ currentDetail.type?.name }}
          </el-descriptions-item>
          <el-descriptions-item label="题目类别" label-class-name="desc-label" />
          <el-descriptions-item label="分数" label-class-name="desc-label">
            {{ currentDetail.score }}
          </el-descriptions-item>
          <el-descriptions-item label="正确答案" label-class-name="desc-label">
            <span style="color: green; font-weight: bold;">
              {{ getOptionLetter(currentDetail.answer_index) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" label-class-name="desc-label">
            {{ currentDetail.created_at }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间" label-class-name="desc-label">
            {{ currentDetail.updated_at }}
          </el-descriptions-item>
        </el-descriptions>
        <div style="margin-top: 10px;">
          <h4>选项</h4>
          <el-card shadow="never">
            <ul style="list-style: none; padding: 0; margin: 0;">
              <li
                v-for="(opt, idx) in currentDetail.content"
                :key="opt.id"
                style="margin-bottom: 8px; display: flex; align-items: center;"
              >
                <span
                  :style="{
                    color: opt.is_ok === 1 ? 'green' : '#333',
                    fontWeight: opt.is_ok === 1 ? 'bold' : 'normal',
                    flexGrow: 1
                  }"
                >
                  {{ getOptionLetter(idx) }}. {{ opt.content }}
                </span>
                <el-button
                  type="text"
                  size="mini"
                  style="color: #F56C6C; margin-left: 10px;"
                  @click="handleDeleteAnswer(currentDetail.id, opt.id)"
                >
                  删除答案
                </el-button>
              </li>
            </ul>
          </el-card>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <el-dialog
      :title="manageForm.isNewAnswer ? '添加新选项' : '编辑'"
      :visible.sync="manageTopicDialogVisible"
      width="800px"
      :close-on-click-modal="false"
      @close="closeManageDialog"
    >
      <div v-if="!manageForm.isNewAnswer">
        <el-form :model="manageForm.topic" label-width="100px">
          <el-form-item label="题目 ID">
            <el-input v-model="manageForm.topic.id" disabled />
          </el-form-item>
          <el-form-item label="题目内容">
            <el-input
              v-model="manageForm.topic.topic"
              type="textarea"
              :rows="4"
              placeholder="请输入题目内容"
            />
          </el-form-item>
        </el-form>
        <el-divider>选项管理</el-divider>
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          style="margin-bottom: 15px;"
          @click="handleAnswerFormOpen()"
        >
          添加新选项
        </el-button>
        <el-card shadow="never" style="max-height: 300px; overflow-y: auto;">
          <ul style="list-style: none; padding: 0; margin: 0;">
            <li
              v-for="(opt, idx) in manageForm.topic.content"
              :key="opt.id"
              style="margin-bottom: 10px; padding: 5px 0; border-bottom: 1px solid #eee; display: flex; align-items: flex-start;"
            >
              <div style="flex-grow: 1; min-width: 0;">
                <span
                  :style="{
                    color: opt.is_ok === 1 ? 'green' : '#333',
                    fontWeight: opt.is_ok === 1 ? 'bold' : 'normal'
                  }"
                >
                  {{ getOptionLetter(idx) }}.
                </span>
                <span style="white-space: pre-wrap; word-break: break-word;">
                  {{ opt.content }}
                  <el-tag v-if="opt.is_ok === 1" size="mini" type="success" style="margin-left: 10px;">
                    正确
                  </el-tag>
                </span>
              </div>
              <div style="flex-shrink: 0; margin-left: 10px;">
                <el-button
                  type="text"
                  size="mini"
                  style="color: #409EFF;"
                  @click="handleAnswerFormOpen(opt)"
                >
                  编辑
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  style="color: #F56C6C;"
                  @click="handleDeleteAnswer(manageForm.topic.id, opt.id, true)"
                >
                  删除
                </el-button>
              </div>
            </li>
          </ul>
        </el-card>
      </div>
      <div v-else>
        <el-form :model="editAnswerForm" label-width="120px">
          <el-form-item :label="editAnswerForm.id ? '选项 ID' : '题目 ID '">
            <el-input :value="editAnswerForm.id || editAnswerForm.topic_id" disabled />
          </el-form-item>
          <el-form-item label="选项内容" required>
            <el-input
              v-model="editAnswerForm.content"
              type="textarea"
              :rows="3"
              placeholder="请输入选项内容"
            />
          </el-form-item>
          <el-form-item label="是否为正确答案">
            <el-switch
              v-model="editAnswerForm.is_ok"
              :active-value="1"
              :inactive-value="0"
              active-text="是"
              inactive-text="否"
            />
            <p style="color: #F56C6C; font-size: 12px; margin: 0; padding-top: 5px;">
              注意：创建/修改为正确答案可能会影响原题目中其他答案的状态。
            </p>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div v-if="!manageForm.isNewAnswer">
          <el-button @click="manageTopicDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleUpdateTopic">保存题目内容</el-button>
        </div>
        <div v-else>
          <el-button @click="manageForm.isNewAnswer = false">返回管理</el-button>
          <el-button type="primary" @click="handleUpdateAnswer">保存选项</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="选择删除操作"
      :visible.sync="deleteTypeDialogVisible"
      width="520px"
      center
      custom-class="delete-dialog-custom"
    >
      <div v-if="currentDeletingRow" class="delete-dialog-content">
        <div class="delete-dialog-header">
          <i class="el-icon-warning-outline warning-icon" />
          <h3 class="delete-dialog-title">请选择删除方式</h3>
          <p class="delete-dialog-subtitle">当前操作题目：</p>
          <p class="delete-dialog-topic">{{ currentDeletingRow.topic.substring(0, 25) }}...</p>
        </div>
        <div class="delete-options-container">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-card
                shadow="hover"
                class="delete-option-card delete-topic-card"
                @click.native="handleConfirmDeleteTopic"
              >
                <div class="delete-option-content">
                  <div class="delete-icon-wrapper delete-topic-icon">
                    <i class="el-icon-document-delete" />
                  </div>
                  <h4 class="delete-option-title">删除整条题目</h4>
                  <p class="delete-option-desc">
                    永久删除该题目及其所有关联的选项和数据
                  </p>
                </div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card
                shadow="hover"
                class="delete-option-card delete-answer-card"
                @click.native="handleCommand('toDetail', currentDeletingRow); deleteTypeDialogVisible = false"
              >
                <div class="delete-option-content">
                  <div class="delete-icon-wrapper delete-answer-icon">
                    <i class="el-icon-remove-outline" />
                  </div>
                  <h4 class="delete-option-title">删除部分选项</h4>
                  <p class="delete-option-desc">
                    进入详情页，只删除题目下的某个错误选项
                  </p>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
      <template #footer>
        <el-button @click="deleteTypeDialogVisible = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getQuestionList, modifyQuestion, deleteQuestion, batchDeletionTestQusetion, deleteAnswer, modifyOrCreateAnswer } from '@/api/question'

export default {
  name: 'QuestionList',
  data() {
    return {
      tableData: [],
      page: 1,
      pageSize: 10,
      total: 0,
      topicInput: '',
      typeInput: '',
      scoreInput: '',
      selectedRows: [],
      detailDialogVisible: false,
      currentDetail: null,
      // 合并后的题目管理弹窗
      manageTopicDialogVisible: false,
      manageForm: {
        // 仅用于展示和修改题目内容
        topic: {
          id: null,
          topic: '',
          content: [] // 暂存选项列表用于展示
        },
        // 用于控制是显示题目内容编辑还是答案编辑表单
        isNewAnswer: false
      },
      editAnswerForm: {
        id: null, // 答案 ID
        content: '', // 答案内容
        is_ok: 0, // 是否为正确答案 (1 是, 0 否)
        topic_id: null // 题目 ID (必填)
      },
      deleteTypeDialogVisible: false,
      currentDeletingRow: null,
      typeMap: {
        '单选': 1,
        '多选': 2,
        '判断': 3
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      const params = {
        page: this.page,
        paginate: this.pageSize
      }
      if (this.topicInput) params.topic = this.topicInput
      if (this.typeInput) {
        const typeId = this.typeMap[this.typeInput]
        if (typeId) {
          params.type = typeId
        } else {
          this.tableData = []
          this.total = 0
          return
        }
      }
      if (this.scoreInput) params.score = this.scoreInput
      try {
        const res = await getQuestionList(params)
        if (res.data) {
          this.tableData = res.data
          this.total = res.meta?.total || 0
        } else {
          this.tableData = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取数据失败:', error)
      }
    },
    handleSearch() {
      this.page = 1
      this.fetchData()
    },
    handleReset() {
      this.topicInput = ''
      this.typeInput = ''
      this.scoreInput = ''
      this.page = 1
      this.fetchData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.page = 1
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.page = val
      this.fetchData()
    },
    getOptionLetter(index) {
      const numIndex = parseInt(index, 10)
      return isNaN(numIndex) ? '' : String.fromCharCode(65 + numIndex)
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    handleCreate() {
      this.$router.push('/question/create')
    },
    handleCommand(command, row) {
      if (command === 'toDetail') {
        this.currentDetail = row
        this.detailDialogVisible = true
      }
    },
    // 打开题目管理弹窗
    handleManageTopic(row) {
      this.manageForm.topic.id = row.id
      this.manageForm.topic.topic = row.topic
      // 深度拷贝选项，以便在管理弹窗中展示最新的数据
      this.manageForm.topic.content = JSON.parse(JSON.stringify(row.content))
      this.manageForm.isNewAnswer = false // 默认显示题目内容编辑
      this.manageTopicDialogVisible = true
    },
    // 提交题目内容修改 (从管理弹窗调用)
    async handleUpdateTopic() {
      if (!this.manageForm.topic.topic.trim()) {
        this.$message.warning('题目内容不能为空')
        return
      }
      try {
        const data = {
          id: this.manageForm.topic.id,
          topic: this.manageForm.topic.topic
        }
        await modifyQuestion(data)
        this.$message.success('题目内容修改成功')
        await this.fetchData()
      } catch (error) {
        console.error('修改题目内容失败:', error)
        this.$message.error('修改题目内容失败，请稍后再试')
      }
      this.manageTopicDialogVisible = false
    },
    // 打开答案编辑/新增表单
    handleAnswerFormOpen(answer) {
      this.manageForm.isNewAnswer = true // 切换到选项编辑/新增视图
      // 重置表单
      this.editAnswerForm.id = null
      this.editAnswerForm.content = ''
      this.editAnswerForm.is_ok = 0
      this.editAnswerForm.topic_id = this.manageForm.topic.id
      if (answer) {
        // 编辑现有选项
        this.editAnswerForm.id = answer.id
        this.editAnswerForm.content = answer.content
        this.editAnswerForm.is_ok = answer.is_ok
      }
    },
    // 提交答案   选项修改
    async handleUpdateAnswer() {
      if (!this.editAnswerForm.content.trim()) {
        this.$message.warning('选项内容不能为空')
        return
      }
      if (!this.editAnswerForm.topic_id) {
        this.$message.error('题目ID缺失，无法创建/修改选项。')
        return
      }
      try {
        const data = {
          id: this.editAnswerForm.id,
          content: this.editAnswerForm.content,
          is_ok: this.editAnswerForm.is_ok,
          topic_id: this.editAnswerForm.topic_id
        }
        // 调用修改/创建答案接口
        await modifyOrCreateAnswer(data)
        this.$message.success(data.id ? '选项修改成功!' : '选项新增成功!')
        // 刷新数据并返回题目管理视图
        await this.fetchData()
        // 找到最新数据并更新 manageForm.topic.content，以刷新选项列表
        const updatedRow = this.tableData.find(item => item.id === this.manageForm.topic.id)
        if (updatedRow) {
          this.manageForm.topic.content = JSON.parse(JSON.stringify(updatedRow.content))
        }
        this.manageForm.isNewAnswer = false // 返回题目管理页面
      } catch (error) {
        console.error('保存选项失败:', error)
        this.$message.error('保存选项失败，请稍后再试')
      }
    },
    // 关闭管理弹窗时，确保状态重置
    closeManageDialog() {
      this.manageForm.isNewAnswer = false
      // 重新获取数据以防万一
      this.fetchData()
    },
    // 处理删除单个答案（选项）
    handleDeleteAnswer(topicId, answerId, isFromManageDialog = false) {
      this.$confirm('确定要删除此选项吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await deleteAnswer({ id: answerId })
          this.$message.success('选项删除成功!')
          await this.fetchData()
          // 如果是从管理弹窗调用的，直接刷新管理弹窗的选项列表
          if (isFromManageDialog) {
            const updatedRow = this.tableData.find(item => item.id === topicId)
            if (updatedRow) {
              this.manageForm.topic.content = JSON.parse(JSON.stringify(updatedRow.content))
            }
          } else if (this.detailDialogVisible) {
            this.detailDialogVisible = false
            this.$message.info('数据已更新，请重新查看详情以刷新选项。')
          }
        } catch (error) {
          this.$message.error('删除选项失败，请稍后重试。')
          console.error('删除选项失败:', error)
        }
      }).catch(() => {
      })
    },
    // 打开删除类型选择弹窗
    handleDeleteRow(row) {
      this.currentDeletingRow = row
      this.deleteTypeDialogVisible = true
    },
    // 确认删除整个题目
    handleConfirmDeleteTopic() {
      const row = this.currentDeletingRow
      this.deleteTypeDialogVisible = false
      this.$confirm(`确定要永久删除题目："${row.topic.substring(0, 20)}..." 吗？同时会删除其绑定的关联数据。`, '警告', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const params = {
            id: row.id,
            delete: 1
          }
          await deleteQuestion(params)
          this.$message.success('题目删除成功!')
          this.fetchData()
        } catch (error) {
          this.$message.error('删除失败，请稍后重试。')
          console.error('删除题目失败:', error)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 批量删除
    handleBatchDelete() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择要删除的题目')
        return
      }
      this.$confirm(`确定要批量删除选中的 ${this.selectedRows.length} 条题目吗？同时会删除其绑定的关联数据。`, '警告', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const ids = this.selectedRows.map(row => row.id)
          const payload = {
            id: ids,
            delete: 1
          }
          await batchDeletionTestQusetion(payload)
          this.$message.success('批量删除成功!')
          this.selectedRows = []
          this.fetchData()
        } catch (error) {
          this.$message.error('批量删除失败，请稍后重试。')
          console.error('批量删除题目失败:', error)
        }
      }).catch(() => {
        this.$message.info('已取消批量删除')
      })
    }
  }
}
</script>
<style scoped lang="scss">
#app {
  padding: 20px;
}
.header {
  background-color: #fff;
  width: 100%;
  margin-bottom: 20px;
  padding: 10px;
  display: flex;
  align-items: center;
}
.content {
  background-color: #fff;
  padding: 20px;
}
.toolbar {
  margin-bottom: 12px;
}
.option-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 4px 8px;
}
::v-deep(.desc-label) {
  text-align: center !important;
  vertical-align: middle;
}
.delete-dialog-content {
  padding: 10px 0;
}
.delete-dialog-header {
  text-align: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}
.warning-icon {
  font-size: 48px;
  color: #ffc53d;
  margin-bottom: 12px;
}
.delete-dialog-title {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #262626;
  font-weight: 600;
}
.delete-dialog-subtitle {
  margin: 0;
  font-size: 14px;
  color: #8c8c8c;
}
.delete-dialog-topic {
  margin: 8px 0 0 0;
  font-size: 14px;
  color: #1890ff;
  font-weight: 500;
  padding: 8px 12px;
  background-color: #f0f8ff;
  border-radius: 4px;
  display: inline-block;
}
.delete-options-container {
  margin-top: 16px;
}
.delete-option-card {
  cursor: pointer;
  transition: all 0.3s ease;
  height: 160px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
    &.delete-topic-card {
      border-color: #ff4d4f;
    }
    &.delete-answer-card {
      border-color: #ffa940;
    }
  }
  ::v-deep(.el-card__body) {
    width: 100%;
    padding: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.delete-option-content {
  text-align: center;
  width: 100%;
}
.delete-icon-wrapper {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 12px;
  font-size: 24px;
  &.delete-topic-icon {
    background-color: #fff2f0;
    color: #ff4d4f;
  }
  &.delete-answer-icon {
    background-color: #fff7e6;
    color: #ffa940;
  }
}
.delete-option-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  .delete-topic-card & {
    color: #ff4d4f;
  }
  .delete-answer-card & {
    color: #ffa940;
  }
}
.delete-option-desc {
  margin: 0;
  font-size: 12px;
  color: #8c8c8c;
  line-height: 1.4;
}
</style>
<style lang="scss">
.delete-dialog-custom {
  .el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #f0f0f0;
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #262626;
    }
  }
  .el-dialog__body {
    padding: 20px;
  }
  .el-dialog__footer {
    padding: 10px 20px 20px;
    border-top: 1px solid #f0f0f0;
    display: none;
  }
}
</style>
